var ByAdd = {
    u: '/bybs',
    uList: '/bybs/list',
    uEdit: '/bybs/add',
    editIndex: -1,
    unitArr: [],
    isDg: 0,
    winThat: undefined,
    dgType: undefined,
    isConfirm: 1
};

$.extend($.fn.datagrid.defaults.editors, {
    house: {
        init: function (container, options) {
            return $('<div style="text-align: center">编辑</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            var rows = ByAdd.dtable.datagrid("getRows");
            var house = rows[ByAdd.editIndex].house;
            return house;
        },
        setValue: function (target, value) {
        },
        resize: function (target, width) {
            $(target).click(function () {
                ByAdd.isDg = 1;
                var rows = ByAdd.dtable.datagrid("getRows");
                var skuId = rows[ByAdd.editIndex].skuId;
                var house = rows[ByAdd.editIndex].house;
                var href = "/wWearhouse/treeGrid?skuId=" + skuId + "&house=" + house + "&type=1&houseId=" + $("#houseId").val();//type 0出库 1入库
                var $dg = $yd.win.create('仓库/库位', href);
                $dg.width = "450px;";
                $dg.height = "520px;";
                $dg.open(function (that, $win) {
                    ByAdd.winThat = that;
                    ByAdd.dgType = "house";
                }, function (that, $win) {
                    ByAdd.saveDgHouse();
                }, function () {
                    if (ByAdd.editIndex > -1) {
                        ByAdd.dtable.datagrid('endEdit', ByAdd.editIndex);
                    }
                    ByAdd.editIndex = -1;
                    ByAdd.isDg = 0;
                    ByAdd.winThat = undefined;
                    ByAdd.dgType = undefined;
                });
            });

            $(target)._outerWidth(width);
        }
    }
});
ByAdd.saveDgHouse = function () {
    var data = KW.getResult();
    var positionId = "";
    if (!$yd.isEmpty(data)) {
        var arr = data.split("_");
        positionId = arr[2];
    }
    ByAdd.dtable.datagrid('updateRow', {
        index: ByAdd.editIndex,
        row: {
            house: data,
            positionId: positionId
        }
    });

    ByAdd.winThat.close();
    ByAdd.isDg = 0;
    ByAdd.winThat = undefined;
    ByAdd.dgType = undefined;
};
ByAdd.dg = function () {
    ByAdd.dtable = $('#part_table');
    ByAdd.dtable.datagrid({
        pagination: false,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        toolbar: [
            {
                text: '增加（Insert）', iconCls: 'icon-add', handler: function () {
                    ByAdd.plus();
                }
            },
            {
                text: '删除（Del）', iconCls: 'icon-remove', handler: function () {
                    ByAdd.remove();
                }
            }
        ],
        columns: [[
            {field: 'positionId', hidden: true},//库位
            {field: 'skuId', checkbox: true},//规格id
            {field: 'goodsName', title: '商品名称', width: 150},
            {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
            {field: 'skus', title: '规格', width: 200},
            {field: 'code', title: '商品编号', width: 80},
            {
                field: 'unit', title: '单位', width: 80, formatter: function (value, row, index) {
                    for (var i = 0; i < ByAdd.unitArr.length; i++) {
                        if (value == ByAdd.unitArr[i].id) {
                            return ByAdd.unitArr[i].text;
                        }
                    }
                    return value;
                }
            },
            {field: 'partsCode', title: '配件编号', width: 80},
            {
                field: 'house',
                title: '<span style="color:blue">库位</span>',
                width: 100,
                editor: {type: 'house'},
                formatter: function (value, row, index) {
                    if ($yd.isEmpty(value)) {
                        return "";
                    }
                    var arr = value.split("_");
                    return "<a style='color:purple'>" + arr[1] + "：" + arr[3] + "</a>";
                }
            },
            // {
            //     field: 'price', title: '成本单价', width: 80, formatter: function (value, row, index) {
            //         return Number(value).toFixed(2);
            //     }
            // },
            {
                field: 'num',
                title: '<span style="color:blue">数量</span><span style="color:red">*</span>',
                width: 80,
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },
            {
                field: 'fee', title: '总金额', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {
                field: 'remark',
                title: '<span style="color:blue">备注</span>',
                width: 100,
                editor: {type: 'textbox'}
            }
        ]],
        onClickCell: function (index, field) {
            if (ByAdd.editIndex != index) {
                if (ByAdd.editIndex > -1) {
                    ByAdd.dtable.datagrid('endEdit', ByAdd.editIndex);
                }
                ByAdd.editIndex = index;
            }
            if (field == "num" || field == "house" || field == "remark") {
                ByAdd.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {
            if (changes) {
                ByAdd.dtable.datagrid('updateRow', {
                    index: index,
                    row: {
                        fee: Number(row.price) * Number(row.num)
                    }
                });
            }
        }
    });

    ByAdd.dtable.datagrid('enableCellEditing');
};
ByAdd.formatDetail = function (value) {
    if ($yd.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:purple' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:purple' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};
ByAdd.refresh = function () {
    window.location.reload();
};
ByAdd.clear = function () {
    var rows = ByAdd.dtable.datagrid("getRows");
    while(rows.length > 0) {
        ByAdd.dtable.datagrid("deleteRow", 0);
        rows = ByAdd.dtable.datagrid("getRows");
    }
};
ByAdd.plus = function () {
    var href = "/mMateriel/searchDg?bindHouseId=" + $("#houseId").val();
    // var $dg = $yd.win.create('商品（绑定当前仓库的才会被查出）', href);
    var $dg = $yd.win.create('商品', href);
    $dg.width = "1050px;";
    $dg.height = "400px;";
    ByAdd.isDg = 1;
    $dg.open(function (that, $win) {
            ByAdd.winThat = that;
            ByAdd.dgType = "goods";
        }, function (that, $win) {
            ByAdd.saveDgGoods();
        }, function () {
            ByAdd.isDg = 0;
            ByAdd.winThat = undefined;
            ByAdd.dgType = undefined;
            document.onkeydown = ByAdd.keyDown;
        }
    );
};
ByAdd.isExist = function (rows, skuId) {
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].skuId == skuId) {
            return true;
        }
    }
    return false;
};
ByAdd.saveDgGoods = function () {
    document.onkeydown = ByAdd.keyDown;

    var data = Goods.getChecked();
    if (data.length == 0) {
        ByAdd.winThat.close();
        ByAdd.isDg = 0;
        ByAdd.winThat = undefined;
        ByAdd.dgType = undefined;
    }

    var rows = ByAdd.dtable.datagrid("getData").rows;
    for (var i = 0; i < data.length; i++) {
        if (!ByAdd.isExist(rows, data[i].skuId)) {
            var dt = data[i];

            //获取成本单价
            $.ajax({
                type: "POST",
                url: "/inRepositoryDetail/getSkuAvgCost2House",
                data: {
                    skuId: data[i].skuId,
                    houseId: $("#houseId").val(),
                },
                dataType: "json",
                async: false,
                success: function (res) {
                    var avgCost = res.avgCost;

                    $.ajax({
                        type: "POST",
                        url: "/inRepositoryDetail/getMaterielHouseByHouseId",
                        data: {
                            materielId: dt.goodsId,
                            houseId: $("#houseId").val(),
                        },
                        dataType: "json",
                        async: false,
                        success: function (result) {
                            var positionId = $yd.isEmpty(result.house) ? 0 : result.house.split("_")[2];
                            ByAdd.dtable.datagrid('appendRow', {
                                skuId: dt.skuId,
                                goodsName: dt.goodsName,
                                goodsId: dt.goodsId,
                                skus: dt.skusName,
                                code: dt.code,
                                partsCode: dt.partsCode,
                                unit: dt.unit,
                                price: avgCost,
                                num: 1,
                                fee: Number(avgCost) * Number(1),
                                house: result.house,
                                positionId: positionId
                            }).datagrid('clearSelections');
                        }
                    });
                }
            });
        }
    }
    ByAdd.winThat.close();
    ByAdd.isDg = 0;
    ByAdd.winThat = undefined;
    ByAdd.dgType = undefined;
};

Array.prototype.contains = function (needle) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};
ByAdd.remove = function () {
    var sels = ByAdd.dtable.datagrid('getChecked')
    if (sels.length < 1) {
        $yd.alert('选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['skuId']);
    });

    $.each(ids, function (i, n) {
        var rows = ByAdd.dtable.datagrid('getRows');
        for (var ii = 0; ii < rows.length; ii++) {
            if (rows[ii].skuId == n) {
                ByAdd.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });
};

ByAdd.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};
ByAdd.save = function () {
    //结束编辑状态
    if (ByAdd.editIndex != undefined && ByAdd.editIndex != -1) {
        ByAdd.dtable.datagrid('endEdit', ByAdd.editIndex);
    }
    if (ByAdd.editIndex != undefined && ByAdd.editIndex != -1) {
        ByAdd.dtable.datagrid('endEdit', ByAdd.editIndex);
    }

    $('#myForm').form('submit', {
        url: ByAdd.uEdit,
        onSubmit: function () {
            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = ByAdd.dtable.datagrid("getRows");
            if (rows.length == 0) {
                $yd.alert("请添加商品");
                return false;
            }

            // for (var i = 0; i < rows.length; i++) {
            //     var row = rows[i];
            //     var house = row.house;
            //     if (ByAdd.isEmpty(house)) {
            //         $yd.alert("商品未配置库位");
            //         return false;
            //     }
            // }

            //封装数据
            $("#goods").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }
        }
    });
};

// 处理按钮
ByAdd.btn = function () {
    var sb = new $yd.SearchBtn($(ByAdd.obtn));
    sb.create('repeat red', '重置（Shift+R）', ByAdd.refresh);
    sb.create('save green', '保存（Shift+S）', ByAdd.save);
};
ByAdd.keyDown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    // console.log("add.js")
};
ByAdd.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }

    if (ByAdd.isDg == 0) {
        if (e.keyCode == 45) {//insert
            ByAdd.plus();
        }
        if (e.keyCode == 46) {//del
            ByAdd.remove();
        }
        if (e.shiftKey && e.keyCode == 83) {
            ByAdd.save();//生单: Shift + S
        }
        if (e.shiftKey && e.keyCode == 82) {
            ByAdd.refresh();
        }
    } else {
        if (e.keyCode == 13) {
            if(ByAdd.dgType == "goods") {
                ByAdd.saveDgGoods();
            } else if(ByAdd.dgType == "house") {
                ByAdd.saveDgHouse();
            }
        } else if (e.keyCode == 27 && ByAdd.winThat) {//ESC
            ByAdd.winThat.close();
        }
    }
};
ByAdd.init = function () {
    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        success: function (data) {
            ByAdd.unitArr = data;
        }
    });

    //默认值
    $("input[name='orderTime']").datebox({
        required: true,
        editable: false,
        value: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate()
    });

    $("#orderType").combobox({
        url: "/sysDict/bybs_type",
        panelHeight:'auto',
        editable:false,
        required:true,
        valueField:'id',
        textField:'text',
        onChange: function (newValue, oldValue) {
            if(ByAdd.isConfirm == 0) {
                return;
            }
            if(!$yd.isEmpty(oldValue)) {
                $.messager.confirm({
                    title: '确认框',
                    border: false,
                    top: 0,
                    msg: "切换单据类型页面会重置，确定切换？",
                    fn: function (r) {
                        if (r) {
                            window.location.href = "/bybs/add?orderType=1";
                        } else {
                            ByAdd.isConfirm = 0;
                            $("#orderType").combobox("setValue", oldValue);
                            ByAdd.isConfirm = 1;
                        }
                    }
                })
            } else {
                window.location.href = "/bybs/add?orderType=1";
            }
        }
    });


    $("#houseId").combobox({
        prompt:'仓库',
        url: "/wWearhouse/list",
        panelHeight:'auto',
        editable:false,
        required:true,
        valueField:'id',
        textField:'name',
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].id);
        },
        onChange: function (newValue, oldValue) {
            var rows = ByAdd.dtable.datagrid("getRows");
            if(rows.length == 0) {
                return;
            }
            if(ByAdd.isConfirm == 0) {
                return;
            }
            if(!$yd.isEmpty(oldValue)) {
                $.messager.confirm({
                    title: '确认框',
                    border: false,
                    top: 0,
                    msg: "切换仓库清除当前仓库已添加的商品，确定切换？",
                    fn: function (r) {
                        if (r) {
                            ByAdd.clear();
                        } else {
                            ByAdd.isConfirm = 0;
                            $("#houseId").combobox("setValue", oldValue);
                            ByAdd.isConfirm = 1;
                        }
                    }
                })
            } else {
                ByAdd.clear();
            }
        }
    });

    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = ByAdd.mouseClick;

    //快捷键
    document.onkeydown = ByAdd.keyDown;
    document.onkeyup = ByAdd.keyUp;

    setTimeout("$('#orderTime').focus()", 500);
    $("a").attr("tabindex", -1);
    $(":checkbox").attr("tabindex", -1);
};
ByAdd.mouseClick = function (e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (ByAdd.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over") && !$(obj).hasClass("datagrid-row-selected")) {
        if (ByAdd.editIndex != -1) {
            ByAdd.dtable.datagrid('endEdit', ByAdd.editIndex);
            ByAdd.editIndex = -1;
        }
    }
};
$(function () {
    ByAdd.obtn = '#part_btn';
    ByAdd.dg(); // 数据表格
    ByAdd.btn(); // 初始化按钮
    ByAdd.init(); // 数据表格
});